package no.hib.bridge.net;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import no.hib.bridge.beans.BoardInfoBean;
import no.hib.bridge.connectors.HtmlToDatabaseConnector;
import no.hib.bridge.gui.SparMainGUI;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author Henning Class used to handle requests from web browsers
 */
public class BridgeHttpHandler extends AbstractHandler {
	SparMainGUI owner;
	String jquery;
	String jqueryMobile;
	String ajax;
	String jqueryMobileCSS;
	static HtmlToDatabaseConnector connector;
	
	public BridgeHttpHandler(SparMainGUI owner) {
		this.owner = owner;
		try {
			connector = new HtmlToDatabaseConnector(owner);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			owner.addMessage("file not found");
		}
		//jquery = resourceStringToByteArray("jquery.js");
		//jqueryMobileCSS = resourceStringToByteArray("jquery.mobile-1.1.0.css");
		//jqueryMobile = resourceStringToByteArray("jquery.mobile-1.1.0.js");
		//ajax = resourceStringToByteArray("ajax.js");
	}

	/**
	 * This handle is used to translate what comes in from the clients web
	 * browser and sends a response
	 */
	@Override
	public void handle(String arg0, Request baseRequest,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		BufferedReader b = request.getReader();

		/*
		 * the requestString is a string containing what the client want to send
		 * to this server
		 */
		String requestString = "";
		String temp1 = "";
		while ((temp1 = b.readLine()) != null) {
			requestString += temp1;
		}

		String url = baseRequest.getRequestURI();
		System.out.println("url: " + url);
		String responseString = "";

		if (url.equals("/checkPlayers"))

		{
			// getting players on the first table
			
			BoardInfoBean bi = new BoardInfoBean();
			JSONObject jo;
			try {
				jo = new JSONObject(requestString);
				bi.setRound(jo.getString("round"));
				bi.setTable(jo.getString("table"));
				bi.setSection(jo.getString("section"));
				responseString = connector.getPlayerNamesAsJSON(bi);
				if (responseString==null) {
					response.setStatus(409);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			response.setContentType("application/json");
			response.getWriter().println(responseString);
			baseRequest.setHandled(true);
		} else if (url.equals("/postPlayers"))
		/*
		 * if the client sends round, table, section, and the 4 player numbers
		 */
		{
			// getting players on the first table
			BoardInfoBean bi = connector
					.setPlayersOnTableFromJSON(requestString);
			responseString = connector.getPlayerNamesAsJSON(bi);

			response.setContentType("application/json");
			response.getWriter().println(responseString.toString());
			baseRequest.setHandled(true);
		} else if (url.equals("/postResult")) {
			connector.postingResult(requestString);
			baseRequest.setHandled(true);
		} 
		
//		else if (url.equals("/")) 
//		/*
//		 * if nothing else is requested, the index file is the response
//		 */
//		{
//			Resource r = Resource.newResource("web-content/index.html");
//			owner.addMessage(r.toString());
//			InputStream is = this.getClass().getClassLoader()
//					.getResourceAsStream("index.html");
//			BufferedReader br = new BufferedReader(new InputStreamReader(is));
//			String temp;
//			while ((temp = br.readLine()) != null) {
//				responseString += "\n" + temp;
//				owner.addMessage("reading");
//			}
//			response.getWriter().println(responseString);
//			baseRequest.setHandled(true);
//		}
	}

	public String resourceStringToByteArray(String s) {
		String returnString = "";

		try {
			InputStream is = this.getClass().getClassLoader()
					.getResourceAsStream(s);

			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String temp;

			while ((temp = br.readLine()) != null) {
				returnString += temp + "\n";
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return returnString;
	}
}
